package com.gatico;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class ProxyDecoder extends ByteToMessageDecoder {
    public enum STATUS {
        GTC, VERSION, TYPE, IP, PORT, LENGTH, DATA
    }

    ProxyProtocol protocol;

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) {
        if (protocol == null) {
            protocol = new ProxyProtocol();
            protocol.status = STATUS.GTC;
        }
        switch (protocol.status) {
            case GTC:
                byte g = byteBuf.readByte();
                byte t = byteBuf.readByte();
                byte c = byteBuf.readByte();
                if (protocol.GTC[0] == g
                        && protocol.GTC[1] == t
                        && protocol.GTC[2] == c) {
                    protocol.status = STATUS.VERSION;
                }
                break;
            case VERSION:
                protocol.v = byteBuf.readInt();
                protocol.status = STATUS.TYPE;
                break;
            case TYPE:
                protocol.type = byteBuf.readByte();
                if (protocol.type == ProxyProtocol.TYPE.HEART.value()) {
                    list.add(protocol);
                    protocol = null;
                    //心跳包处理
                } else if (protocol.type == ProxyProtocol.TYPE.HTTP.value() || protocol.type == ProxyProtocol.TYPE.TCP.value()) {
                    protocol.status = STATUS.IP;
                } else if (protocol.type == ProxyProtocol.TYPE.MSG.value()) {
                    protocol.status = STATUS.LENGTH;
                }
                break;
            case IP:
                protocol.ip = byteBuf.readInt();
                protocol.status = STATUS.PORT;
                break;
            case PORT:
                protocol.port = byteBuf.readInt();
                protocol.status = STATUS.LENGTH;
                break;
            case LENGTH:
                protocol.length = byteBuf.readInt();
                protocol.data = new byte[protocol.length];
                protocol.status = STATUS.DATA;
                break;
            case DATA:
                System.out.println(protocol.length);
                if(byteBuf.readableBytes() < protocol.length){
                    break;
                }
                byteBuf.readBytes(protocol.data, 0, protocol.length);
                System.out.println(new String(protocol.data));
                list.add(protocol);
                protocol = null;
                break;
            default:
                throw new RuntimeException("协议错误");
        }

    }
}
